﻿using IntelligentDataCollection.Device;
using IntelligentDataCollection.Models;
using IntelligentDataCollection.Tool;
using System.Net;
using System.Net.Sockets;

namespace HDSmartCommunity.Device
{
    public abstract class AbstractCOMDevice : AbstractDevices
    {
        private Socket client;
        private Thread thread;

        public override bool ConnectServer(string serverIP, int port)
        {
            try
            {
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.Connect(serverIP, port);
                //server.ReceiveTimeout = 10000;
                thread = new Thread(StartReceive);
                thread.Start(client);
                int index = DeviceSerialData.device_list.FindIndex(x => x.DeviceIP == serverIP && x.DevicePort == port);
                if (index > -1)
                {
                    DeviceInfo Deviceinfo = DeviceSerialData.device_list[index];
                    Deviceinfo.ConnectFlag = true;
                    Deviceinfo.socket = client;
                    DeviceSerialData.device_list[index] = Deviceinfo;
                }
                return true;
            }
            catch (Exception e)
            {
                LogHelper.Log("连接恒大异常" + e.ToString());
                return false;
            }
        }

        //接收消息
        public void StartReceive(object obj)
        {
            byte[] buffer = new byte[2048];
            int length = 0;
            while (true)
            {
                try
                {
                    length = client.Receive(buffer);
                    if (length == 0)
                    {
                        break;
                    }
                    else
                    {
                        IPEndPoint remoteEP = client.RemoteEndPoint as IPEndPoint;
                        string deviceip = remoteEP.Address.ToString();
                        int port = remoteEP.Port;
                        int device_index = DeviceSerialData.device_list.FindIndex(x => x.DeviceIP == deviceip && x.DevicePort == port);
                        if (device_index > -1)
                        {
                            InsertExcelData(Untils.ToHexs(buffer.Skip(0).Take(length).ToArray()), DeviceSerialData.device_list[device_index].DeviceName);
                        }
                    }
                }
                catch (Exception ex)
                {
                    continue;
                }
            }
        }

        public bool InsertExcelData(string data, string devicename)
        {
            try
            {
                string path = AppDomain.CurrentDomain.BaseDirectory;
                string dirpath = path + @"wwwroot/TestLog/" + devicename;
                string filepath = dirpath + @"/" + devicename + "_" + DateTime.Now.ToString("yyyy-MM-dd") + ".csv";
                //生成目录
                // 判断文件是否存在，不存在则创建，否则读取值显示到txt文档
                if (!File.Exists(filepath))
                {
                    //创建文件夹
                    if (Directory.Exists(dirpath) == false)//如果不存在就创建file文件夹
                    {
                        Directory.CreateDirectory(dirpath);
                    }
                    FileStream fs1 = new FileStream(filepath, FileMode.Create, FileAccess.Write);//创建写入文件 
                    fs1.Close();
                }
                File.AppendAllTextAsync(filepath, DateTime.Now.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss:fff") + "," + data + "\r\n");
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex.ToString());
            }
            return true;
        }
    }
}
